package com.link.base.base.crowd.service;

import com.link.base.base.crowd.dao.mybatis.mapper.CrowdAccntDetMapper;
import com.link.base.base.crowd.model.CrowdAccntDet;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.ExportColumn;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.modules.export.ExportFactory;
import com.link.core.modules.export.ExportWriter;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 人群消费者明细表-
 *
 * @author 张宇浩
 * @date 2019/06/01 15:30
 */
@Service
public class CrowdAccntDetServiceImpl extends BasicServiceImpl<CrowdAccntDet> implements CrowdAccntDetService {

    @Resource
    private CrowdAccntDetMapper crowdAccntDetMapper;

    @Override
    public BasicMapper<CrowdAccntDet> getBasicMapper() {
        return crowdAccntDetMapper;
    }

    @Override
    public List<CrowdAccntDet> queryAllAccountByTypeA(CrowdAccntDet crowdAccntDet, String type) throws Exception {
        List<CrowdAccntDet> sloveResult = new ArrayList<>();
        Long crowdId = crowdAccntDet.getCrowdId();
        if ("OpenId".equals(type)) {
            List<CrowdAccntDet> queryResult = crowdAccntDetMapper.queryAllAccountByTypeA(crowdAccntDet);
            if (queryResult.size() > 0) {
                for (CrowdAccntDet item : queryResult) {
                    CrowdAccntDet entity = new CrowdAccntDet();
                    if (null == item || StringUtils.isBlank(item.getKeyId()) || StringUtils.isBlank(item.getAppId())) {
                        continue;
                    }
                    entity.setCrowdId(crowdId);
                    entity.setAppId(item.getAppId());
                    entity.setKeyId(item.getKeyId());
                    entity.setType("OpenId");
                    entity.setCrowdAccntId(item.getCrowdAccntId());
                    entity.setId(keyGenerateService.keyGenerate());
                    entity.setCreatedBy(crowdAccntDet.getCreatedBy());
                    entity.setLastUpdatedBy(crowdAccntDet.getLastUpdatedBy());
                    sloveResult.add(entity);
                }
            }
        }
        if ("MobilePhone".equals(type)) {
            List<CrowdAccntDet> queryResult = crowdAccntDetMapper.queryAllAccountPhoneByTypeA(crowdAccntDet);
            if (queryResult.size() > 0) {
                for (CrowdAccntDet item : queryResult) {
                    CrowdAccntDet entity = new CrowdAccntDet();
                    if (null == item || StringUtils.isBlank(item.getKeyId())) {
                        continue;
                    }
                    entity.setCrowdId(crowdId);
                    entity.setKeyId(item.getKeyId());
                    entity.setType("MobilePhone");
                    entity.setCrowdAccntId(item.getCrowdAccntId());
                    entity.setId(keyGenerateService.keyGenerate());
                    entity.setCreatedBy(crowdAccntDet.getCreatedBy());
                    entity.setLastUpdatedBy(crowdAccntDet.getLastUpdatedBy());
                    sloveResult.add(entity);
                }
            }
        }
        return sloveResult;
    }

    @Override
    public void batchInsert(List<CrowdAccntDet> list) throws Exception {
        crowdAccntDetMapper.batchInsertAccntDet(list);
    }

    /**
     * 导出人群包数据
     *
     * @param crowdId    人群id
     * @param openidFlag 是否（Y/N）导出openid
     * @param phoneFlag  是否（Y/N）导出手机号
     * @return csv文件url的list
     */
    @Override
    public List<String> exportByCrowd(Long crowdId, String openidFlag, String phoneFlag) throws Exception {
        List<String> urls = new ArrayList<>();
        if (StringUtils.equals(openidFlag, "Y")) {
            String openIdUrl = exportOpenIdToFile(crowdId);
            urls.add(openIdUrl);
            LCLogger.info().withMessageKey("service.exportByCrowd")
                    .withMessage("crowdId:" + crowdId + ";openIdUrl:" + openIdUrl).flush();
        }
        if (StringUtils.equals(phoneFlag, "Y")) {
            String mobilePhoneUrl = exportMobilePhoneToFile(crowdId);
            urls.add(mobilePhoneUrl);
            LCLogger.info().withMessageKey("service.exportByCrowd")
                    .withMessage("crowdId:" + crowdId + ";mobilePhoneUrl:" + mobilePhoneUrl).flush();
        }
        return urls;
    }

    /**
     * 导出openid
     *
     * @param crowdId 人群包id
     * @return csv文件url
     */
    private String exportOpenIdToFile(Long crowdId) throws Exception {
        QueryParams qps = new QueryParams();
        qps.addFilter(new Filter("crowdId", Filter.OP_EQUAL, String.valueOf(crowdId)));
        qps.addFilter(new Filter("type", Filter.OP_EQUAL, "OpenId"));
        qps.setPage(1);
        qps.setPageFlag(true);

        List<ExportColumn> exportColumns = new ArrayList<>();
        ExportColumn column1 = new ExportColumn();
        column1.setTitle("微信appid");
        column1.setField("appId");
        column1.setOrder(0);
        exportColumns.add(column1);

        ExportColumn column2 = new ExportColumn();
        column2.setTitle("微信openid");
        column2.setField("keyId");
        column2.setOrder(1);
        exportColumns.add(column2);

        qps.setExportColumns(exportColumns);
        return exportByQps(qps);
    }

    /**
     * 导出手机号
     *
     * @param crowdId 人群包id
     * @return csv文件url
     */
    private String exportMobilePhoneToFile(Long crowdId) throws Exception {
        QueryParams qps = new QueryParams();
        qps.addFilter(new Filter("crowdId", Filter.OP_EQUAL, String.valueOf(crowdId)));
        qps.addFilter(new Filter("type", Filter.OP_EQUAL, "MobilePhone"));
        qps.setPage(1);
        qps.setPageFlag(true);

        List<ExportColumn> exportColumns = new ArrayList<>();
        ExportColumn column1 = new ExportColumn();
        column1.setTitle("手机号");
        column1.setField("keyId");
        column1.setOrder(0);
        exportColumns.add(column1);

        qps.setExportColumns(exportColumns);
        return exportByQps(qps);
    }

    /**
     * 导出csv文件
     *
     * @param qps 参数对象
     * @return csv文件url
     * @throws Exception 异常
     */
    private String exportByQps(QueryParams qps) throws Exception {
        ExportWriter exportWriter = ExportFactory.newInstance(qps);
        CrowdAccntDet example = BasicModel.transformClass(CrowdAccntDet.class, qps);

        while (!qps.getStopExport()) {
            List<CrowdAccntDet> list = this.queryByExamplePage(example);
            if (qps.getPage() == 1) {
                qps.setTotal(example.getTotal());
            }
            exportWriter.wirteData(list);
            example.setPage(qps.getPage());
            example.setTotalFlag(qps.getTotalFlag());
        }
        return exportWriter.getUrlPath();
    }
}

